﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace TiecCuoi
{
    public partial class FormLoaiSanh : Form
    {
        //Data base
        private SqlConnection _CNN;
        //Bien giao dien form
        bool _IsAdd = true;
        //Color error
        Color _color1, _color2;
        bool _IsERROR = false;
        //thong tin nhap
        string _MaSo;
        long _dongia;
        public FormLoaiSanh(SqlConnection cnn, bool isAdd)
        {
            InitializeComponent();
            _color1 = Color.White;
            _color2 = Color.Red;
            //true -> Add
            //false -> Edit
            _IsAdd = isAdd;
            _CNN = cnn;
            if (_IsAdd)
                textBox_maso.Text = CreateMa();
            HienThi();
            LoadDataView();
        }

        //---------------------Hien thi ADD/Edit
        private void HienThi()
        {
            if (_IsAdd)//Add
            {
                //an button Edit
                this.B_EditLS.Visible = false;
                //an button delete
                this.B_DeleteLS.Visible = false;
                //label huong dan
                L_errGia.Text = "Nhập đơn giá";
                L_errGia.Visible = true;
                L_errGia.ForeColor = Color.Blue;

            }
            else//Edit
            {
                //an button Add
                this.B_AddLS.Visible = false;
            }


        }
        //--------------------Load Data Hien thi Listview
        private void LoadDataView()//khi load form/delete/edit/add
        {
            ListViewItem item;
            bool bool_mau = false;
            int i = 0;
            try
            {
                string ham = "select MaLoaiSanh,DonGiaBanToiThieu from LOAISANH";
                i++;
                SqlCommand select = new SqlCommand(ham, _CNN);
                SqlDataReader read = select.ExecuteReader();
                while (read.Read())
                {
                    item = new ListViewItem(read[0].ToString());
                    item.SubItems.Add(read[1].ToString());
                    if (bool_mau == false)
                        item.BackColor = Color.White;
                    else
                        item.BackColor = Color.FromArgb(245, 204, 102);
                    bool_mau = !bool_mau;
                    L_viewLS.Items.Add(item);
                    i++;
                }
                read.Close();
                select.Dispose();
                read.Dispose();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }
        //-------------------Reset null all tectbox
        private void ResetTextBox()//khi an Cancle va OK,delete
        {
            if(!_IsAdd)
            {
                textBox_maso.Text = "";
            }
            else
            {
                textBox_maso.Text = CreateMa();
            }
            textbox_dongia.Text = "";
            textbox_dongia.Focus();
        }

        //Chac chan ten mon an chua ton tai
        private void textBox_Ten_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        //Dam bao nhap so duong, tu dong them dau thap phan
        private void textbox_giatoithieu_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && (int)e.KeyChar != 44 && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        //-----------------ham tu dong tach so
        public void TachSo(TextBox luong)
        {
            string txt, txt1;
            txt1 = luong.Text.Replace(",", "");
            txt = "";
            int n = txt1.Length;
            int dem = 0;
            for (int i = n - 1; i >= 0; i--)
            {
                if (dem == 2 && i != 0)
                {
                    txt = "," + txt1.Substring(i, 1) + txt;
                    dem = 0;
                }
                else
                {
                    txt = txt1.Substring(i, 1) + txt;
                    dem += 1;
                }
            }
            luong.Text = txt;
            luong.SelectionStart = luong.Text.Length;
        }
        //---------------insert mon an
        private void InsertLS(string ma,long dongia)
        {
            try
            {
                string cmd = "INSERT INTO LOAISANH VALUES(@MA,@DONGIA)";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@MA", ma);
                command.Parameters.AddWithValue("@DONGIA", dongia);
                command.ExecuteNonQuery();
                command.Dispose();
                MessageBox.Show("Đã thêm loại sảnh", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.None);
            }
            catch (Exception emon)
            {
                MessageBox.Show(emon.Message);
            }
        }
        //-------------------------------------update mon an
        private void UpdateLS(string ma,long dongia)
        {
            if (L_viewLS.FocusedItem == null)
                MessageBox.Show("Hãy chọn dòng truớc", "Thông báo");
            else
            {
                try
                {
                    string ham = "Update LOAISANH set DonGiaBanToiThieu=@gia where MaLoaiSanh=@maso";
                    SqlCommand add = new SqlCommand(ham, _CNN);
                    add.CommandType = CommandType.Text;
                    add.Parameters.AddWithValue("@gia", dongia);
                    add.Parameters.AddWithValue("@maso", ma);
                    add.ExecuteNonQuery();
                    add.Dispose();
                    MessageBox.Show("Cập nhật dữ liệu thành công", "Thông Báo");
                }
                catch (Exception e2)
                {
                    MessageBox.Show(e2.Message);
                }
            }
        }
        //----------------------------------Delete mon an
        private void DeleteLS(string ma)
        {
            if (L_viewLS.FocusedItem == null)
                MessageBox.Show("Hãy chọn dòng truớc", "Thông báo");
            else
            {
                try
                {
                    string ham = "delete from LOAISANH where MaLoaiSanh=@maso";
                    SqlCommand add = new SqlCommand(ham, _CNN);
                    add.CommandType = CommandType.Text;
                    add.Parameters.AddWithValue("@maso", ma);
                    add.ExecuteNonQuery();
                    add.Dispose();
                    MessageBox.Show("Đã xóa loại sảnh " + ma, "Thông Báo");
                }
                catch (Exception e2)
                {
                    MessageBox.Show(e2.Message);
                }
            }
        }
        //Tao ma mon ăn
        private string CreateMa()
        {
            string maso = string.Empty;
            try
            {
                string cmd = "select top(1) *  from LOAISANH ORDER BY MaLoaiSanh desc";
                SqlCommand command = new SqlCommand(cmd, _CNN);
                SqlDataReader read = command.ExecuteReader();
                if (read.Read())
                {
                    maso = read[0].ToString();
                }
                if (maso == "")
                {
                    read.Close(); read.Dispose();
                    return "LS001";
                }
                read.Close(); read.Dispose();
                maso = maso.Substring(2, 3);
                int so = Convert.ToInt32(maso);
                for (int i = so + 1; i <= 999; i++)
                {
                    maso = i.ToString();
                    if (maso.Length == 1)
                        maso = "LS00" + maso;
                    if (maso.Length == 2)
                        maso = "LS0" + maso;
                    if (maso.Length == 3)
                        maso = "LS00" + maso;

                    string cmd2 = "select MaLoaiSanh from LOAISANH Where MaLoaiSanh=@mama ";
                    SqlCommand command2 = new SqlCommand(cmd2, _CNN);
                    command2.Parameters.AddWithValue("@mama", maso);
                    SqlDataReader read2 = command2.ExecuteReader();
                    if (read2.Read())
                    {
                        read2.Close();
                        read2.Dispose();
                        continue;
                    }
                    read2.Close();
                    read2.Dispose();
                    return maso;

                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return "loi";
        }


        //-------------------------------------Xu kien Form-------------------------------
        //------------------ADD
        private void B_AddLS_Click(object sender, EventArgs e)
        {
            if (!CheckNULLValues())//khong loi thi them
            {
                //Lay thong tin
                string tam;
                _MaSo = textBox_maso.Text;
                tam = textbox_dongia.Text;
                tam = tam.Replace(",", "");
                _dongia = Convert.ToInt64(tam);
                //insert
                InsertLS(_MaSo, _dongia);
                //reload list view
                L_viewLS.Items.Clear();
                LoadDataView();
                ResetTextBox();
            }
        }
        //------------------Edit
        private void B_EditLS_Click(object sender, EventArgs e)
        {
            if (!CheckNULLValues())//khong loi thi them
            {
                //Lay thong tin
                string tam;
                _MaSo = textBox_maso.Text;
                tam = textbox_dongia.Text;
                tam = tam.Replace(",", "");
                _dongia = Convert.ToInt64(tam);
                //update
                UpdateLS(_MaSo, _dongia);
                //reload list view
                L_viewLS.Items.Clear();
                LoadDataView();
                ResetTextBox();
            }
        }
        //------------------delete
        private void B_DeleteLS_Click(object sender, EventArgs e)
        {
            if (L_viewLS.FocusedItem != null)//phai chon truoc
            {
                //Lay thong tin
                _MaSo = textBox_maso.Text;
                //delete
                DeleteLS(_MaSo);
                //reload list view
                L_viewLS.Items.Clear();
                LoadDataView();
                ResetTextBox();
            }
        }
        //------------------Cancel
        private void B_CancelMA_Click(object sender, EventArgs e)
        {
            ResetTextBox();
        }

        //Dam bao nhap so o don gia
        private void textbox_giatoithieu_TextChanged(object sender, EventArgs e)
        {
            TachSo(textbox_dongia);
            if (textbox_dongia.Text.Length > 11)//nhap so tien qua lon
            {

                L_errGia.Text = "Đơn giá quá lớn";
                L_errGia.Visible = true;
                L_errGia.ForeColor = Color.Red;
                MessageBox.Show("Đơn giá quá lớn", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textbox_dongia.Text = "";
            }
            else if (textbox_dongia.Text.Length == 0)
            {
                L_errGia.Text = "Nhập đơn giá";
                L_errGia.Visible = true;
                L_errGia.ForeColor = Color.Blue;
            }
            else if (textbox_dongia.Text.Length < 5)//nhap so tien qua nho
            {
                L_errGia.Text = "Đơn giá quá nhỏ";
                L_errGia.Visible = true;
                L_errGia.ForeColor = Color.Blue;
            }
            else//hop le
            {
                L_errGia.Visible = false;
            }

        }
        //Check null values
        private bool CheckNULLValues()
        {
            if (textbox_dongia.Text.Length < 5)
            {
                textbox_dongia.BackColor = _color2;
                L_errGia.Text = "Đơn giá quá nhỏ";
                _IsERROR = true;
            }
            if (_IsERROR)//hien thong bao loi
            {
                MessageBox.Show("Thông tin nhập không hợp lệ", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textbox_dongia.BackColor = _color1;
                L_errGia.Visible = false;
                _IsERROR = false;
                return true;
            }
            return false;

        }

        private void L_viewS_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_IsAdd == false && L_viewLS.FocusedItem != null)
            {
                this.textBox_maso.Text = this.L_viewLS.Items[L_viewLS.FocusedItem.Index].SubItems[0].Text.Trim();
                this.textbox_dongia.Text = this.L_viewLS.Items[L_viewLS.FocusedItem.Index].SubItems[1].Text.Trim();
            }
        }

    }
}
